package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class QuanZiApiImpl implements QuanZiApi{
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private VideoApi videoApi;
    //
    @Override
    //好友动态的publish结果
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {

        //按照时间分页查询时间线表
        PageInfo<Publish> pageInfo  = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //条件
        Pageable pageable = PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

       if (CollUtil.isEmpty(timeLines)){
           //没查到数据
           return pageInfo;
       }
       //获取id集，方便查发布表
        List<ObjectId> objectIdList = new ArrayList<>();
        for (TimeLine timeLine : timeLines) {
            objectIdList.add(timeLine.getPublishId());
        }
        //获取该ID的时间线表下的发布信息集合
        Query queryPublish =Query.query(Criteria.where("id").in(objectIdList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish,Publish.class);

        pageInfo.setRecords(publishList);
        return pageInfo;
    }
    //发布动态保存
    @Override
    public String savePublish(Publish publish) {
        //校验传递的对象是否有填充必选选项
        if (!ObjectUtil.isAllNotEmpty(publish.getText(),publish.getUserId())){
            return null;
        }
        //写入发布表

        //设置主键ID，也就是发布ID
        publish.setId(ObjectId.get());
        try {
            //设置pid自动增长
            publish.setPid(this.idService.createId(IdType.PUBLISH)); //自增长ID
            long createTime = System.currentTimeMillis();//创建时间
            publish.setCreated(createTime);//创建时间
            this.mongoTemplate.save(publish);//存入发布表

            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());//主键id
            album.setCreated(createTime);//发布时间
            album.setPublishId(publish.getId());//发布ID
            this.mongoTemplate.save(album,"quanzi_album_"+publish.getUserId());

            //异步写入时间线表
            this.timeLineService.saveTimeLine(publish.getUserId(),publish.getCreated(),publish.getId()); //发布id，发布时间，主键id
        } catch (Exception e) {
            //TODO 事务回滚，暂时不实现
            log.error("发布动态失败 publish = "+publish,e);
        }
            return publish.getId().toHexString();
    }
    //推荐列表集合
    public PageInfo<Publish> queryRecommendPublishList(Long userId,Integer page,Integer pageSize){
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //获取推荐数据  pid
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = this.redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }
        //查询到的pid进行分页处理
        List<String> pids = StrUtil.split(data, ',');
        //计算分页
        //[0, 10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size()); //结束
        //获取pid的集合
        List<Long> pidLongList = new ArrayList<>();

        for (int i  = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        //判断是有有推荐的有效数据
        if (CollUtil.isEmpty(pidLongList)){
            return pageInfo;
        }
        //根据pid获取publish集合

        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        //判断是否能查到
        if (CollUtil.isEmpty(publishList)){
            return pageInfo;
        }
        System.out.println(publishList);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    //查询该发布id的发布内容
    public Publish queryPublishById(String id) {

        return this.mongoTemplate.findById(new ObjectId(id),Publish.class);
    }

    @Override //点赞
    public Boolean likeComment(Long userId, String publishId) {

        if (this.queryUserIsLike(userId,publishId)){//判断该用户是否已经对此发布动态点赞
            return false;
        }
        //保存 comment数据
        Boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result){
            return false;//保存失败也就是点赞失败
        }
        //修改redis中的点赞信息 ,点赞数量+1
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,1);

        //用户是否点赞,标记点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        return true;
    }
    //获取点赞的key
    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }
    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    @Override //取消点赞
    public Boolean disLikeComment(Long userId, String publishId) {
        Boolean result = this.queryUserIsLike(userId, publishId);
       if (!result){
           return false;
       }
        //删除评论数据
        Boolean removeResult = this.removeComment(userId, publishId, CommentType.LIKE);
        if (!removeResult) {
            return false;
        }
        //修改Redis中的数据

        //修改点赞数
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //删除该用户对此条动态的点赞标记
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }
    //从mongoDB中删除该用户的点赞标记
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        int type = commentType.getType();
        Query query = Query.query(Criteria.where("userId").is(userId).and("publishId").is(new ObjectId(publishId))
        .and("commentType").is(type));
        long deletedCount = this.mongoTemplate.remove(query, Comment.class).getDeletedCount();
        return deletedCount>0;
    }

    @Override //查询点赞次数
    public Long queryLikeCount(String publishId) {
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LIKE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isAllNotEmpty(data)){
            return Convert.toLong(data);//点赞次数
        }
        //redis如果查不到再去数据库确认
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        //查询到的数据再写到redis中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;
    }
    //mongodb查询数量
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(commentType.getType()));
        return this.mongoTemplate.count(query,Comment.class);
    }

    @Override //确认该发布内容是否被用户点赞
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)){
            boolean result = StrUtil.equals(Convert.toStr(data), "1");//查到数据说明点赞过
            return result;
        }
        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if(count == 0){
            return false;
        }
        //写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    /**
     * 保存Comment
     * @return
     */
    private Boolean saveComment(Long userId, String publishId, CommentType commentType,String content){
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());//自己的主键id
            comment.setUserId(userId);//评论者id
            comment.setPublishId(new ObjectId(publishId));//发布id
            comment.setCommentType(commentType.getType());//评论类型
            comment.setContent(content); //评论内容
            comment.setCreated(System.currentTimeMillis());//本次评论创建时间
            Publish publish = this.queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if(ObjectUtil.isNotEmpty(myComment)){
                    comment.setPublishUserId(myComment.getUserId());
                }else{
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
                    if(ObjectUtil.isNotEmpty(video)){
                        comment.setPublishUserId(video.getUserId());
                    }else{
                        // 其他情况，直接返回
                        return false;
                    }
                }
            }
            //TODO 其他内容暂时不做填充
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //查询该用户是否已经喜欢
        if (this.queryUserIsLove(userId, publishId)) {
            return false;
        }

        //喜欢
        boolean result = this.saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result) {
            return false;
        }

        //喜欢成功后，修改Redis中的总的喜欢数
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //标记用户已经喜欢
        hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        if (!this.queryUserIsLove(userId, publishId)) {
            //如果用户没有喜欢，就直接返回
            return false;
        }

        boolean result = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            //删除失败
            return false;
        }

        //删除redis中的记录
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        this.redisTemplate.opsForHash().increment(redisKey, CommentType.LOVE.toString(), -1);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }

        //查询count
        Long count = this.queryCommentCount(publishId, CommentType.LOVE);

        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return StrUtil.equals(Convert.toStr(value), "1");
        }

        //查询mongodb
        Query query = Query.query(Criteria.where("publishId")
                .is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //标记用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    @Override //查询评论---分页
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageRequest pagerequest = PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.asc("creat6ed")));
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("commentType").is(CommentType.COMMENT.getType())).with(pagerequest);
        //查询评论列表
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> commentPageInfo = new PageInfo<>();
        commentPageInfo.setPageNum(page);
        commentPageInfo.setPageSize(pageSize);
        commentPageInfo.setRecords(comments);
        return commentPageInfo;
    }
    //保存评论
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId,publishId,CommentType.COMMENT,content);
    }
    /**
     * 根据id查询Comment对象
     *
     * @param id
     * @return
     */
    private Comment queryCommentById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Comment.class);
    }

    @Override
    public Long queryCommentCount(String publishId) {
        return this.queryCommentCount(publishId, CommentType.COMMENT);
    }
    /**
     * 查询对我的点赞消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,CommentType.LIKE,page,pageSize);
    }
    /**
     * 查询对我的喜欢消息列表
     *
     * @return
     */

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LOVE,page,pageSize);
    }
    /**
     * 查询对我的评论消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,CommentType.COMMENT,page,pageSize);
    }

    @Override//查询相册表
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        Pageable pageRequest = PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        //根据id查相册表
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albumList)){
            return pageInfo;
        }
        List<Object> publishId = CollUtil.getFieldValues(albumList, "publishId");
        Query queryPublish = Query.query(Criteria.where("id").in(publishId)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    //根据评论类型返回对应集合
    private PageInfo<Comment> queryCommentListByUser(Long userId,CommentType commentType,Integer page,Integer pageSize){
        Pageable pageRequest = PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc("created")));
        Query query = new Query(Criteria.where("publishUserId").is(userId).and("commentType").is(commentType.getType())).with(pageRequest);
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        pageInfo.setRecords(comments);
        return pageInfo;
    }
}
